package com.aerospace.serviceprovider.lambda;

import org.junit.jupiter.api.Test;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class Lambda {

    @Test
    public void thread() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("Before Java8,too much code for too little to do");
            }
        });

        new Thread(() -> System.out.println("In JAVA8, Lambda expression rocks !!")).start();


    }

    //集合迭代
    @Test
    public void iterTest() {
        List<String> languages = Arrays.asList("java", "scala", "python");
        //before java8
        for (String each : languages) {
            System.out.println(each);
        }
        //after java8
        languages.forEach(x -> System.out.println(x));
        languages.forEach(System.out::println);
    }

    //
    @Test
    public void mapTest() {
        List<Double> cost = Arrays.asList(10.0, 20.0, 30.0);
        cost.stream().map(x -> x + x * 0.05).forEach(x -> System.out.println(x));
    }


    @Test
    public void mapReduceTest() {
        List<Double> cost = Arrays.asList(10.0, 20.0, 30.0);
        double allCost = cost.stream().map(x -> x + x * 0.05).reduce((sum, x) -> sum + x).get();
        System.out.println(allCost);
    }


    @Test
    public void filterTest() {
        List<Double> cost = Arrays.asList(10.0, 20.0, 30.0, 40.0);
        List<Double> filteredCost = cost.stream().filter(x -> x > 25.0).collect(Collectors.toList());
        filteredCost.forEach(x -> System.out.println(x));

    }

    public static void filterTest(List<String> languages, Predicate<String> condition) {
        languages.stream().filter(x -> condition.test(x)).forEach(x -> System.out.println(x + " "));
    }

    public static void main(String[] args) {
        List<String> languages = Arrays.asList("Java", "Python", "scala", "Shell", "R");
        System.out.println("Language starts with J: ");
        filterTest(languages, x -> x.startsWith("J"));
        System.out.println("\nLanguage ends with a: ");
        filterTest(languages, x -> x.endsWith("a"));
        System.out.println("\nAll languages: ");
        filterTest(languages, x -> true);
        System.out.println("\nNo languages: ");
        filterTest(languages, x -> false);
        System.out.println("\nLanguage length bigger three: ");
        filterTest(languages, x -> x.length() > 4);

    }
}